<?php
namespace Cyfy\Modules\News;
use \Cyfy\Modules\Locale\Locale;
use \Cyfy\Modules\DibiPager\DibiPager;
use \Cyfy\Modules\BasicContent\Content;
use \Cyfy\Modules\Objects\Collapsible;

class Module extends \Cyfy\Module
{
    const IMAGE_DIR = "news/";
    const IMAGE_ORIGINAL_DIR = "news/orig/";
    const IN_BLOCK = 2;
    const CROP_TEXT_TO = 600;
    
    static $settings = array("perPage", "inBlock", "imageWidth", "imageHeight");


    static function blocks($name = "")
    {
        switch($name)
        {
            case "short":
                return self :: getShort();
            case "full":
                return self :: getList();
            default:
                return array(
                    "short" => self :: t(400),
                    "full" => self :: t(410)
                );
        }
    }
    
    
    static function administration($name = "")
	{
		// something selected?
        switch($name)
        {
            case "create":
                $form = new Forms\Create();
                //$form -> setData(array("time" => new \datetime() ));
                return $form -> show(); 
            case "settings":
                $form = new Forms\Settings();
                $form -> setDataFromConstants(self :: $settings);
                return $form -> show(); 
            case "":
                return array(
                    "create" => array("name" => self :: t(10), "description" => self :: t(20), "permission"=> "write and edit"),
                    "settings" => array("name" => self :: t(30), "description" => self :: t(40), "permission" => "administration")
                );
		}	
	}
    
    static function ajax($name)
    {
        switch($name)
        {
            case "entries":
                return self :: ajaxEntries();
                
            case "deleteEntry":
                return self :: ajaxDeleteEntry($_POST["nid"]);
        }
    
    }
    
    
    static function get($name)
    {
        switch($name)
        {
            case "detail":
                return self :: detail(\Cyfy\Cyfy ::  arg(1));
                break;
            case "edit":
                return self :: edit(\Cyfy\Cyfy ::  arg(1));
                break;

            case "list":
                return self :: listOf();
        }
    }
    
    
    
    static private function listOf()
    {
		\Cyfy\Template :: setTitle( self :: t(50));
        
        if(\Cyfy\Cyfy ::  permission("News", "write and edit"))
        {
            $form = new Forms\Create();
            $form -> setData(array("time" => new \datetime()));
            $c = new Collapsible();
            $c -> setData(self :: t(60), $form->show(), true);
            $output = $c -> show();
        }
        
        $output .= "<h2>" . self :: t(50) . "</h2>\n";
        $pager = new DibiPager("news", self :: Constant("perPage"));		
        $pager -> ajaxCall("News","entries", '#news-entries');
        
        
        $output .= "<div id=\"news-entries\">" . self :: ajaxEntries() . "</div>";
        
        $output .= $pager -> pager("SELECT count(*) FROM [:cyfy:News]");			
        
        
        return $output;
       
    }
    
    static private function getShort()
    {
        $newsUrl = \Cyfy\Cyfy ::  getPath("news");
        $output = "<h3><span><a href=\"{$newsUrl}\">" . self :: t(70) . "</a></span></h3>\n";
    
        $limit = (self :: constant("inBlock")) ? self::constant("inBlock") : self :: IN_BLOCK;

        // select entries
        $result = \dibi :: query("SELECT [image], [title], [short], [nid] FROM [:cyfy:News] ORDER BY [time] DESC LIMIT %i", $limit);
	
        // entries itetator
		foreach($result as $n)
		{
            /*
            $readMore = self :: t(80);
            if($n["image"])
            {
                $i = \Cyfy\Cyfy ::  getSourcePath(\Cyfy\Cyfy :: $filesDir . self :: IMAGE_DIR . $n["image"]);
                $image = "<div class=\"image\"><img src=\"" . $i . "\" alt=\"{$n["title"]}\"></div>";
            }
            else
            {
                $image = "";
            }
            $image
            <p class="read-more"><a href="{$link}">{$readMore}</a></p>
            
            */
            $link = \Cyfy\Cyfy ::  getPath("news/" . $n["nid"]);
            
            // building a entry... templates someday??
$output .= <<<OUTPUT
<div class="news-entry"> 
    <h4 class="title"><a href="{$link}">{$n["title"]}</a></h4>
    <p class="description">{$n["short"]}</p>
</div>             
OUTPUT;
        }
        $output .= "<p class=\"read-all\"><a href=\"{$newsUrl}\">" . self :: t(1000) . "</a></p>";
        return $output;
    }






    
    static private function ajaxEntries()
    {
        // pager declaration and ajax
        $pager = new DibiPager("news", self :: Constant("perPage"));		
        $pager -> ajaxCall("News","entries", '#news-entries');
        
        $result = $pager -> query("SELECT * FROM [:cyfy:News] ORDER BY [time] DESC");
	
		// if no results, exit with no entries found
		if(count($result) == 0){
			return \Cyfy\Message :: get( self :: t(90), \Cyfy\Message::WARNING);
		}
		

        
        // entries itetator
		foreach($result as $n)
		{
            $link = \Cyfy\Cyfy ::  getPath("news/" . $n["nid"]);
            if($n["image"]){
                $i = \Cyfy\Cyfy ::  getSourcePath(\Cyfy\Cyfy :: $filesDir . self :: IMAGE_DIR . $n["image"]);
                $image = "<div class=\"image\"><img src=\"" . $i . "\" alt=\"{$n["title"]}\"></div>";
            }else{
                $image = "";
            }
            $time = Locale :: getTime($n["time"], true);
            // building a entry... templates someday??
$output .= <<<OUTPUT
<div class="news-entry"> 
    <p class="time">$time</p>
    <h3 class="title"><a href="{$link}">{$n["title"]}</a></h3>
    <a href="{$link}">$image</a>
    <p class="description">{$n["short"]}</p>
</div>             
OUTPUT;
        }
        return $output;
    }
    
    
    
    
    
    
    
    
    
    static private function detail($nid)
    {
         
         
        $result = \dibi :: query("SELECT * FROM [:cyfy:News] WHERE nid = %i", $nid);	
        
        // if not found
        if(count($result) == 0)
        {
            $_SESSION["404url"] = "news/" . $nid;
            \Cyfy\Cyfy :: redirectTo('error/404');
            return false;
        }
        $n = $result -> fetch();
		
        $c = Content :: load($n["bcid"]);
        if(!$c) return false;
        
        // get
        \Cyfy\Template :: setTitle($c -> getTitle());
        $output .= "<h2>" . $c -> getTitle() . "</h2>\n";
        if($n["image"])
        {
            $i = \Cyfy\Cyfy ::  getSourcePath(\Cyfy\Cyfy :: $filesDir . self :: IMAGE_DIR . $n["image"]);
            $output  .= "<div class=\"news-image\"><img src=\"" . $i . "\" alt=\"{$n["title"]}\"></div>";
        }
        $output .= "<p class=\"news-time\">" . Locale :: getTime($n["time"], true) . "</p>\n";
        
        $output .= $c -> get("", false);
        
        // more edit options:
        if(\Cyfy\Cyfy ::  permission("News", "write and edit") && ($c -> isEditable() || $c -> isDeletable()))
        {
            $output .= "<ul class=\"bcMoreEditOptions\">";
            if($c -> isEditable()){
                $output .= "<li> <a class=\"button\" href=\"" . \Cyfy\Cyfy ::  getPath("news/{$nid}/edit") . "\">" . self :: t(100) . " </a></li>";
            }
            if($c -> isDeletable()){
                $output .= "<li> <a class=\"button\" href=\"#\" onclick=\"if(confirm('" . self :: t(121, array($n["title"])) . "')){ Cyfy.ajax('News', 'deleteEntry', '', 'nid={$nid}', 'Cyfy.redirectTo(\'news\');');} return false;\">" .  self :: t(110) . " </a></li>";
            }
            $output .= "</ul>";
        }
        return $output;
    
    }
    
    
    
    
    
    
    
    static private function edit($nid)
    {
        if(!\Cyfy\Cyfy ::  permission("News", "write and edit"))
        {
            \Cyfy\Cyfy ::  noPermission();
            return false;
        }
                
        $result = \dibi :: query("SELECT * FROM [:cyfy:News] WHERE nid = %i", $nid);	
        
        if(count($result) == 0){
            \Cyfy\Message :: set(self :: t(210), \Cyfy\Message::ERROR);
            return false;
        }
        $n = $result -> fetch();
		
        $c = Content :: load($n["bcid"]);
        if(!$c) return false;
        
        $n["text"] = $c -> getContent();
        
        $form = new Forms\Edit();
        $form -> setData($n);
        
        $output .= "<h2>". self :: t(221, $n["title"]) ."</h2>";
        $output .= $form -> show();
        return $output;
    }
    
    static private function ajaxDeleteEntry($nid)
    {
        if(!\Cyfy\Cyfy ::  permission("News", "write and edit"))
        {
            \Cyfy\Cyfy ::  noPermission();
            return false;
        }
                
        $result = \dibi :: query("SELECT [nid], [bcid], [image] FROM [:cyfy:News] WHERE nid = %i", $nid);
        // if no results, exit with no entries found
		if(count($result) == 0){
			\Cyfy\Message :: set( self :: t(210), \Cyfy\Message::ERROR);
            return false;
		}
		
        $e = $result -> fetch();
        
        
        if(Content :: deleteStatic($e["bcid"]))
        {
            // delete thumbnails
            if($e["image"]){
                \Cyfy\Cyfy ::  delete(\Cyfy\Cyfy :: $filesDir . self :: IMAGE_DIR . $e["image"]);
                \Cyfy\Cyfy ::  delete(\Cyfy\Cyfy :: $filesDir . self :: IMAGE_ORIGINAL_DIR . $e["image"]);
            }
            // delete from db
            \dibi :: query("DELETE FROM [:cyfy:News] WHERE nid = %i", $nid);
            
			\Cyfy\Message :: set( self :: t(320));
            return true;
        }
        \Cyfy\Cyfy ::  noPermission();
        return false;
    }
    
    static function rebuildThumbnails()
    {
        $w = self :: constant("imageWidth");
        $h = self :: constant("imageHeight");
        // checking
        if(!$w || !$h)
        {
            return false;
        }
            
        // load dir
        $files = scandir(\Cyfy\Cyfy :: $filesDir . self :: IMAGE_ORIGINAL_DIR);
        array_shift($files);
        array_shift($files);
        
        // resize them
        foreach($files as $filename)
        {
            $i = new \Cyfy\Modules\Image\Image(\Cyfy\Cyfy :: $filesDir . self :: IMAGE_ORIGINAL_DIR . $filename);
            $i -> resize($w, $h);
            $i -> saveAs(\Cyfy\Cyfy :: $filesDir . self :: IMAGE_DIR . $filename);
            $i -> close();
        }
        
        return true;
    }
}
